sugarfreeControllers.controller('ReceiptController', ['$scope','$log','$http','$filter', '$timeout', '$q','HttpService','ngTableParams','Utils','TimeService','DictionarySerivce','ClassTypes',
          function($scope,$log,$http, $filter, $timeout, $q,httpService,ngTableParams, Utils,timeService,dictionarySerivce,classTypes) {

  
  $scope.closePopupBox = function(){	closePopupBox(); 	};
  
  $scope.orderDetailByLessonId = function(receipt){orderDetailByLessonId(receipt);};
  
  $scope.orderDetailByLesson = function(lesson){orderDetailByLesson(lesson);};
  
  $scope.setTimeRange = function(rangeName){	setTimeRange(rangeName);		};
  
  $scope.getReceipts = function (start, end){	getReceipts(start, end);		};

	
  function getReceipts(start, end) {
    var _start = start.replace(/-/g,'');
    var _end = end.replace(/-/g,'');
    
    if(_end > timeService.parse(new Date(),'yyyyMMdd')){
    	alert('结束日期不能大于当前日期!');
    	return;
    }
    
    if(_start > _end){
    	alert('查询开始日期不能大于结束日期');
    	$scope.startDate = $scope.endDate;
    	return;
    }
    var classType = !$scope.condition.classTypeValue?'':$scope.condition.classTypeValue;
    var coachId = !$scope.condition.coachId?'':$scope.condition.coachId;
    
    var _apiUrl = "receipt/query?";
    var _query = "beginDay="+ _start +
                 "&endDay="+ _end +
                 "&classType=" + classType + 
                 "&coachId=" + coachId;

    var _url = _apiUrl + _query;
    Utils.setProcessParclose(true);
		$http.get(_url).then(function(rsps){
			$scope.allReceipts = rsps.data;
		    console.log("$scope.allReceipts",$scope.allReceipts);
		    angular.forEach($scope.allReceipts.list, function(item) {
		      var bTime = item.lesson.beginTime;
		      console.info("bTime",bTime);
		      if(bTime){
		    	  item.lesson.tBeginDate = bTime.substr(0,4) + "-" + bTime.substr(4,2) + "-" + bTime.substr(6,2);
		    	  item.lesson.tBeginTime = bTime.substr(8,2)+ ":" + bTime.substr(10,2);
		    	  
		    	  var tEndDateTime = item.lesson.tBeginDate +" "+item.lesson.tBeginTime+":00";
		    	  var date = new Date(tEndDateTime);
		    	  date.setMinutes(date.getMinutes() + item.lesson.duration);
		    	  item.lesson.tEndTime = timeService.parse(date,'HH:mm');
		      }
		    });
		    $scope.tableParams.total($scope.allReceipts.length);
		    $scope.tableParams.page(1);
		    $scope.tableParams.reload();
		    //Utils.setProcessParclose(false);
		},function(rsps){
				alert('查询出错');
			  Utils.setProcessParclose(false);
		});
		
		_apiUrl = "statistics/paid?";
		_url = _apiUrl + _query;
		
		$http.get(_url).then(
			function(rsps){
				$scope.paidBean = rsps.data;
				console.info("rsps",rsps);
			},function(rsps){
				console.info("rsps",rsps);
				alert("查询出错");
				Utils.setProcessParclose(false);
			});
		
		var expandParams = {beginDay:_start,endDay:_end,classType:classType,coachId:coachId};
		$scope.tableParamsLessons = getTableParams(lessonsIncomeByPage,expandParams);
		angular.extend($scope.tableParamsLessons.$params,{nowdate:new Date()});
		$scope.tableParamsLessons.reload();
  }
  
  var lessonsIncomeByPage = function(params){
		$log.info("params",params);
		var page = params.page();
		var count = params.count();
		var beginDay = params.beginDay;
		var endDay = params.endDay;
		var classType = params.classType;
		var coachId = params.coachId;
		var _queryParam ="page="+ page +
						 "&limit="+ count +
						 "&beginDay=" + beginDay +
						 "&endDay=" + endDay +
						 "&classType=" + classType +
						 "&coachId=" + coachId;
		console.log("_queryParam",_queryParam);
		return $http.get("lesson/query/income?" + _queryParam);
	};

 
  function setTimeRange(rangeName){
	  var endDate = new Date();
	  var startDate = new Date();
	  switch (rangeName) {
		case 'week':
			startDate.setDate(startDate.getDate() - 7);
			//$scope.startDate = $filter('date')(startDate, "yyyy-MM-dd");
			break;
		case 'submonth':
			startDate.setDate(startDate.getDate() - 15);
			break;
		case 'month':
			startDate.setDate(startDate.getDate() - 30);
			break;
		default:
			break;
		}
	  $scope.startDate = $filter('date')(startDate, "yyyy-MM-dd");
	  $scope.endDate = $filter('date')(endDate, "yyyy-MM-dd");
  }
  
  
  function orderDetailByLessonId(receipt){
	  $scope.selectTr = receipt.lessonReceipt.lesson.id;
	  $scope.selectedReceipt = receipt;
	  Utils.setParclose(true);
	  $scope.isPopupBox = !$scope.isPopupBox;
	  console.log("receipt。。",receipt);
	  $scope.receiptsBylesson = $filter('filter')($scope.allReceipts,{lesson:{id:receipt.lessonId}}, true);
	  console.log("$scope.receiptsBylesson",$scope.receiptsBylesson);
	  console.log("$scope.selectedReceipt",$scope.selectedReceipt);
  }
  
  
  function orderDetailByLesson(lesson){
  	var orderProcElement = {
  		getDataFn:function(params){
  			var lessonId = params.lessonId;
  			var count = params.count();
  			var page = params.page();
  			var _url = "receipt/query?lessonId="+ lessonId +
	  					 		 "&status=5" +
	  					 		 "&isPage=1" +
	  					 		 "&page=" + page +
	  					 		 "&limit=" +count;
	  		return httpService.get(_url);
  		},
  		procResult:function(data){
  			console.info('procResult',data);
  			return data;
  		},
  		expandParams:{
  			lessonId:lesson.id
  		}
  	};
  	
  	$scope.tableParamsReceipt = getTableParamsNew(orderProcElement);
  	angular.extend($scope.tableParamsReceipt.$params,{nowdate:new Date()});
		$scope.tableParamsReceipt.reload();
		
  	
	  $scope.isPopupBox = !$scope.isPopupBox;
		$scope.selectedLesson = lesson;	  
	  var _url = "receipt/query?lessonId="+lesson.id +
	  					 "&status=5";
	  Utils.setParclose(true);
	  httpService.get(_url).then(function (rsps){
	  	$scope.receiptsBylesson = rsps.data;
	  	console.info('success rsps',rsps);
	  	//Utils.setParclose(false);
	  },function(rsps){
	  	console.info('rsps',rsps);
	  	alert('查询出错！');
	  	Utils.setParclose(false);
	  });
  }
  
  function getTableParamsNew(procElement){
  		console.info('procElement',procElement);
			return new ngTableParams({
				page: 1,            // show first page
				count: 5           // count per page
			},{
				counts: [],
				total: 0, // length of data
				getData:function($defer,params){
//					Utils.setProcessParclose(true);
					params = angular.extend(params,procElement.expandParams);
					procElement.getDataFn(params).success(function (data){
							console.info('datadata',data);
							var result = procElement.procResult(data);
							params.total(result.total);
							$defer.resolve(result.list);
					});
					Utils.setProcessParclose(false);
				}
			});
	}
  

  function closePopupBox(){
	  Utils.setParclose(false);
	  $scope.isPopupBox = !$scope.isPopupBox;
  }
  
  
  function getTableParams(getDataFn,expandParams){
			return new ngTableParams({
				page: 1,            // show first page
				count: 10           // count per page
			},{
				counts: [],
				total: 0, // length of data
				getData:function($defer,params){
//					Utils.setProcessParclose(true);
					params = angular.extend(params,expandParams);
					getDataFn(params).success(function (data){
							console.info("success",data);
							//console.info('1<<1',1<<1);
							var pageinfo = data;
							params.total(pageinfo.total);
							angular.forEach(pageinfo.list,function(item){
								item.beginTime = timeService.patten(item.beginTime);
							});
							$defer.resolve(pageinfo.list);
					});
					Utils.setProcessParclose(false);
				}
			});
	}
  
  
  
  function initData() {
  	var endDate = new Date();
  	var startDate = new Date();
  	startDate =  startDate.setDate(endDate.getDate() - 15);
  	$scope.startDate = $filter('date')(startDate, "yyyy-MM-dd");
  	$scope.endDate = $filter('date')(endDate, "yyyy-MM-dd");
  	
  	console.info('$scope.startDate',$scope.startDate);
  	console.info('$scope.endDate',$scope.endDate);
  	
	  $scope.allReceipts = [];
	  // receipt table func filter and sorting   分页
	  $scope.tableParams = new ngTableParams({
		  page: 1,            // show first page
		  count:10           // count per page
	  }, {
		  counts: [],
		  total: 0, // length of data
		  getData: function($defer, params) {
			  // use build-in angular filter
			  //var orderedData = params.sorting ?$filter('orderBy')($scope.allReceipts, params.orderBy()):$scope.allReceipts;
			  var orderedData = $filter('orderBy')($scope.allReceipts,'lesson.beginTime',true);
					  var lessonReceipts = [],sumPaid=0,sumCoupon=0,notPayment=0,notPaymentCoupon=0;
					  angular.forEach(orderedData, function(item) {
						  var found = $filter('filter')(lessonReceipts,{lessonId:item.lesson.id}, true);
						  if(found.length){
							  found[0].totalPaidInBean += item.paidInBean;
							  found[0].totalPaidInCoupon += item.paidInCoupon;
							  found[0].totalNumber += item.number;
						  }else{
							  lessonReceipts.push({lessonId:item.lesson.id,
								  				   lessonReceipt:item,
								  				   lessonTime:timeService.patten(item.lesson.beginTime),
								  				   totalPaidInBean:item.paidInBean,
								  				   totalPaidInCoupon:item.paidInCoupon,
								  				   totalNumber:item.number
								  				 });
						  }
						  sumPaid += item.paidInBean;
						  sumCoupon += item.paidInCoupon;
						  if(item.lesson.status !==2 ){
							  notPayment += item.paidInBean;
							  notPaymentCoupon += item.paidInCoupon;
						  }
					  });
					  //$log.info("notPayment",notPayment);
					  //$log.info("lessonReceipts",lessonReceipts);
					  $scope.total = {paidBeans: sumPaid, couponBeans: sumCoupon};
					  $scope.notTotal={notPayment:notPayment,notPaymentCoupon:notPaymentCoupon};
					  
					  
					  var count_lessonReceipts = lessonReceipts.slice((params.page() - 1) * params.count(), params.page() * params.count());
					  params.total(lessonReceipts.length); // set total for recalc pagination
					  $defer.resolve(count_lessonReceipts);
		  }
	  });
	  
	  $scope.condition = {};
	  $scope.getReceipts($scope.startDate, $scope.endDate);
	  $scope.classTypes = classTypes.array;
	  dictionarySerivce.getCoachs().success(function(data){
		  $scope.coachs = data;
		  console.log("$scope.coachs",$scope.coachs);
	  });
  }

  
  initData();
}]);